#include "locationview.h"
#include "ui_locationview.h"

LocationView::LocationView(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::LocationView)
{
    ui->setupUi(this);

    table=TD_LOCATION;
    homeLocation=UserProfile().getProfile();
    userModel=new QSqlTableModel(this);
    systemModel=new QSqlTableModel(this);

    ui->userView->setEditTriggers(QTableView::NoEditTriggers);
    ui->userView->setModel(userModel);
    ui->systemView->setEditTriggers(QTableView::NoEditTriggers);
    ui->systemView->setModel(systemModel);

    updateView();
    createMenu();
}

LocationView::~LocationView()
{
    delete ui;
}

void LocationView::generateMenu()
{

}

void LocationView::openLocation(const QString &location)
{
    if(QDir(location).exists())
    {
        ui->location->setText(location);
        QDesktopServices::openUrl(QUrl(location));
    }
    else
        ui->location->setText(location + " 不存在");
}

void LocationView::updateView()
{
    userModel->setTable(table);
    userModel->setFilter(QString("category='%1'").arg("user"));
    userModel->select();

    ui->userView->hideColumn(0);   //id
    ui->userView->hideColumn(1);  //category
    userModel->setHeaderData(2,Qt::Horizontal,"label");   //label
    ui->userView->hideColumn(3);   //detail
    userModel->setHeaderData(4,Qt::Horizontal,"distro");   //addition

    systemModel->setTable(table);
    systemModel->setFilter(QString("category='%1'").arg("system"));
    systemModel->select();

    ui->systemView->hideColumn(0);   //id
    ui->systemView->hideColumn(1);  //category
    systemModel->setHeaderData(2,Qt::Horizontal,"label");   //label
    ui->systemView->hideColumn(3);   //detail
    systemModel->setHeaderData(4,Qt::Horizontal,"distro");   //addition
}

void LocationView::on_userView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString detail=index.sibling(index.row(),3).data().toString();
        if(detail.contains("%1"))
            detail=detail.arg(homeLocation);
        openLocation(detail);
    }
}

void LocationView::on_systemView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString detail=index.sibling(index.row(),3).data().toString();
        openLocation(detail);
    }
}
